

package com.evenmo.string;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * This is Description 生产者消费者模式
 * 同步容器，提供put和get方法及getCount方法，
 * 支持2个生产者线程，10个消费者线程
 * @author moyongjun
 * @date 2020/01/05
 */
public class Thread_pro_custom <T>{

final private LinkedList<T> container= new LinkedList<>();

final private int MAX_SIZE=10;//最大容量

    private int count=0;


    public synchronized void put(T t){
        while(container.size()==MAX_SIZE){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        container.add(t);
        count++;
        //通知消费消费
        this.notifyAll();
    }

    public synchronized T get(){
        T t=null;
        while (container.size()==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        t=container.removeFirst();
        count--;
        //通知生产者生产
        this.notifyAll();
        return t;
    }

    public static void main(String[] args) {

        Thread_pro_custom tpc=new Thread_pro_custom();

        for (int i = 0; i < 10; i++) {

            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" "+"获取的元素："+tpc.get());
            },"消费者"+i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        for (int i = 0; i < 2; i++) {

            new Thread(()->{

                for (int j = 0; j < 10; j++) {


                    tpc.put(j);
                }
            },"生产者"+i).start();
        }
    }


}
